package com.xf.tourismapp.utils;


import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;

import java.io.IOException;

import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 基于 Okhttp 网络请求框架封装网络访问的工具类
 */
public class OkHttpUtils {

    private final Handler mHandler;
    private final OkHttpClient mClient;
    //声明类的变量
    private static volatile OkHttpUtils sOkHttpUtils;

    //私有构造，超时参数设置移到Builder
    private OkHttpUtils() {
        mHandler = new Handler(Looper.getMainLooper());
        mClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(5000, TimeUnit.MILLISECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    //网络访问单例模式singleton，暴露外界访问的方法,双层锁
    public static OkHttpUtils getInstance(){
        if(sOkHttpUtils == null){
            synchronized (OkHttpUtils.class){
                if(sOkHttpUtils == null){
                    //创建对象
                    sOkHttpUtils = new OkHttpUtils();
                }
            }
        }
        //如果不等于空直接返回对象,符合单例的概念
        return sOkHttpUtils;
    }

    //创建回调接口
    public interface OkHttpCallBackLinener{
        void failure(Exception e);
        void success(String json);
    }

    /*封装post参数定义三个 */
    public void doPost(String path, Map<String,String> map , final OkHttpCallBackLinener callBackLinener ){
        //创建表单
        FormBody.Builder builder = new FormBody.Builder();

        if(map != null){
            for (String key : map.keySet() ) {
                //添加键值对
                builder.add(key,map.get(key));
            }
        }
        //完成表单的创建
        FormBody formBody = builder.build();

        Request request = new Request.Builder()
                .post(formBody)
                .url(path)
                .build();

        Call call = mClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull final IOException e) {
                //更新到主线程
                mHandler.post(() -> callBackLinener.failure(e));
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                //保险
                if(response != null & response.isSuccessful()){
                    final String json = response.body().string();

                    if(callBackLinener != null){
                        //切换到主线程更新
                        mHandler.post(() -> callBackLinener.success(json));
                    }
                }
            }
        });
    }

    //封装get参数定义两个,一个是URL网址   一个实现接口的对象
    public void doGet(String path, final OkHttpCallBackLinener callBack){

        Request request = new Request.Builder()
                .get()
                .url(path)
                .build();

        Call call = mClient.newCall(request);
        Log.i("NETDEBUG",path);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull final IOException e) {
                //切换到主线程
                mHandler.post(() -> callBack.failure(e));
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull final Response response) throws IOException {

                final String json = response.body().string();
                if(response != null){
                    //切换到主线程
                    mHandler.post(() -> {
                        Log.i("NETDEBUG",json);
                        callBack.success(json);
                    });

                }
            }
        });
    }
}
